package com.gu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.boot.exception.DiyException;
import com.gu.service.MessageSenderService;
import org.springframework.stereotype.Service;


import java.util.Map;

/**
 * Description:
 *
 * @Autor: Rolin
 * datetime: 06-09-7:18
 */
@Service
public class MessageSenderImpl implements MessageSenderService {

    //阿里控制台访问Api验证：
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            return new com.aliyun.dysmsapi20170525.Client(config);
        } catch (Exception e) {
            e.printStackTrace();
            throw new DiyException("444","阿里云验证失败");
        }
    }


    @Override
    public boolean send(String phoneNum, String sms_code, Map<String, Object> randomMap) {

        com.aliyun.dysmsapi20170525.Client client = this.createClient("LTAI5tLGmiu1XYytf5qGgnTY", "aJEQqXGGSxjOWxsP75YaJ25lZDFgAU");
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode(sms_code)
                .setPhoneNumbers(phoneNum)
                .setTemplateParam(JSONObject.toJSONString(randomMap));
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
            return true ;
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            return false;
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            return false;
        }

    }
}
